
from tag import BaseTag , FrameSlottedAlohaTag
from reader import BinaryTagReader , FrameSlottedAlohaTagReader
import time
import settings
from settings import logger

import operateCount as operate
def run_simulation(num_tags=10, reader_cls=BinaryTagReader, tag_cls=BaseTag):
    # Create a collection of tags，生成num_tags个标签实例
    tags = [tag_cls() for _ in range(num_tags)]
    tag_reader = reader_cls()

    #Current epoch time
    min_time = int(time.time())
    max_time=min_time + settings.SIMULATED_DURATION
    #logger.info(f"min_time:{min_time},durtion:{settings.SIMULATED_DURATION} , max_time:{max_time}")
    
    for t in tags:
        #为每个标签随机分配在`[min_time, max_time]`范围内的传输时间。
        t.generate_time(min_time, max_time)
        logger.debug(f"TIME: {t.transmit_time}, tag: {t.id}")

    transmission_map = {}
    '''输入是标签列表，输出是字典，键：传输时间，值是所有具有相同传输时间的标签'''
    for t in tags:
        if not transmission_map.get(t.transmit_time):
            transmission_map[t.transmit_time] = [t]
        else:
            transmission_map[t.transmit_time].append(t)

    slots = 0
    for t, tags in transmission_map.items():#遍历所有的键值对
        if len(tags) <= 1:
            #logger.info(f"len(tags):{len(tags)}")
            continue

        logger.debug(f"[NEW COLLISION] De-colliding: {tags} at time: {t}")
        slots += tag_reader.manage_collision(tags)#无论
       

    #logger.info(f"Tags: {num_tags}\t Total Slots: {slots}")
    return num_tags, slots

def frameAlohaSimulate(num_tags=10, reader_cls=FrameSlottedAlohaTagReader, tag_cls=FrameSlottedAlohaTag):
    
    reader = reader_cls()
    tags = [tag_cls () for _ in range(num_tags)] #生成num_tags个标签对象
    
    Total_slots_used = reader.manage_collision(tags)
    #希望生成柱状图，横坐标为标签数，每一柱形表示各个运算的数量

    shift_count, mul_count, div_count,index_count = operate.get_stats()
    #logger.info(f"shift_count:{shift_count}\t mul_count:{mul_count}\t div_count:{div_count}\t index_count:{index_count}\t ")
    return num_tags, Total_slots_used, shift_count, mul_count, div_count, index_count

